package cn.foolishbird.hamal.frame.util;

import cn.foolishbird.hamal.frame.bsassert.info.SysInfo;
import cn.foolishbird.hamal.frame.exception.ExceptionFactory;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * @author Eric
 * @version 1.0
 * @date 2020-09-29
 */
@Slf4j
public class JacksonJSON {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    static {
        MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    public static String toJSONString(Object obj) {
        try {
            return MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("convert POJO to JSONString failure, desc:{}", e);
            throw  ExceptionFactory.businessException(SysInfo.JSON_CONVERT_ERROR);
        }
    }

    public static <T> T fromJson(String json, Class<T> type) {
        T pojo;
        try {
            pojo = MAPPER.readValue(json, type);
        } catch (IOException e) {
            log.error("convert JSON to POJO failure, desc:{}", e);
            throw  ExceptionFactory.businessException(SysInfo.JSON_CONVERT_ERROR);
        }
        return pojo;
    }

}
